<?php

namespace app\admin\controller;
use app\common\controller\Admin;
use app\ads\controller\Api;
use think\Validate;

/**
 * 数据
 *
 * @Author 小邓
 * @DateTime 2022-11-05
 */
class Statistics extends Admin {

	public function _initialize() {
		parent::_initialize();
		$this->url = "https://bowen.qingguo959.com/api/tuiguang/getinfo";
        $this->key = 'TpzXabIqd8u^1crS';

    }


    public function _empty(){
        $action = ACTION_NAME;
        $pageSize = 30;
        $consumeCount = 0;
        $incomeOne = 0;
        $incomeCount = 0;
        $params = request()->param();
        // 默认获取当天数据
        $startDate = isset($params['startdata']) ? $params['startdata'] : date('Y-m-d', time());
        $endDate = isset($params['enddata']) ? $params['enddata'] : date('Y-m-d', time());

        $list  = db('gzh_material_detail')->order('id desc')->whereBetween('extension_date', [$startDate, $endDate]);
        $this->assign(compact('startDate', 'endDate'));
        $detailList = db('gzh_material_detail')->whereBetween('extension_date', [$startDate, $endDate]);
        if (isset($params['family']) && $params['family'] != 999999) {
            $list = $list->where('family', $params['family']);
            $detailList = $detailList->where('family', $params['family']);
        }
        if (isset($params['effect']) && $params['effect'] != 999999) {
            $list = $list->where('effect', $params['effect']);
            $detailList = $detailList->where('effect', $params['effect']);
        }
        if (isset($params['userid']) && $params['userid'] != 999999) {
            $list = $list->where('uid', $params['userid']);
            $detailList = $detailList->where('uid', $params['userid']);
        }
        $uid   = session('user_auth.uid');
        if(!in_array($uid, [1,52,53])){
            $list = $list->where('uid', $uid);
            $detailList = $detailList->where('uid', $uid);
        }
        $list = $list->order('create_time', 'desc')->paginate( $pageSize, false, [ 'type'=> 'page\Page' ,'query' => request()->param()] );
        $detailList = $detailList->where('refresh', 1)->column('id,consume,extension_id');
        $data = [];
        // 去重获取公众号id，根据id获取公众号名称
        $gzhList = db('gzh_official_account')->distinct(true)->column('id, name');
        $book = db('ads_material_book')->column('title,roi', 'id');
        $data['list'] = [];
        foreach ($list as $k => $v) {
            $v['uname'] = db('member')->where('uid', $v['uid'])->value('username') ?? '';
            $v['effect'] = $v['effect'] ?? 3;
            if ($v['refresh'] == 1) {
                $consumeCount += $v['consume'];
            }
            $v['income'] = 0;
            $v['one_proportion'] = 0;
            $v['two_proportion'] = 0;
            $v['three_proportion'] = 0;
            $v['income_proportion'] = 0;
            $countOne = 0;
            $countTwo = 0;
            $countThree = 0;
            $v['gzh_name'] = $gzhList[$v['official_account_id']]?? '';
            $v['book_name'] = $book[$v['book_id']]['title']?? '';

            $v['extension_id'] = explode(',', $v['extension_id']);

            $extensionInfo = db('gzh_extension')->where('detail_id', $v['id'])->select();
            $extensionInfo = array_column($extensionInfo, null, 'extension_id');
            foreach ($v['extension_id'] as $kk) {
                if (!isset($extensionInfo[$kk])) {
                    $v['income'] = 0;
                    $v['income_one'][] = 0;
                    $v['income_two'][] = 0;
                    $v['income_three'][] = 0;
                    continue;
                }
                $v['income'] += $extensionInfo[$kk]['income']; // 总收入
                $v['income_one'][] = $extensionInfo[$kk]['income_one'];
                $v['income_two'][] = $extensionInfo[$kk]['income_two'];
                $v['income_three'][] = $extensionInfo[$kk]['income_three'];
                $countOne = $countOne + $extensionInfo[$kk]['income_one'];
                $countTwo = $countTwo + $extensionInfo[$kk]['income_two'];
                $countThree = $countThree + $extensionInfo[$kk]['income_three'];
                if ($v['refresh'] == 1) {
                    $incomeOne += $extensionInfo[$kk]['income_one'];
                    $incomeCount += $extensionInfo[$kk]['income'];
                }
            }
            // 营收/消耗=回收率
            $v['one_proportion'] = $countOne == 0 ? 0 : round($countOne / $v['consume'] * 100);
            $v['two_proportion'] = $countTwo == 0 ? 0 : round($countTwo / $v['consume'] * 100);
            $v['three_proportion'] = $countThree == 0 ? 0 : round($countThree / $v['consume'] * 100);
            $v['income_proportion'] = $v['income'] == 0 ? 0 : round($v['income'] / $v['consume'] * 100);
            $roi = isset($book[$v['book_id']]) ? json_decode($book[$v['book_id']]['roi'], true) : [];
            if (isset($roi['百度'])) {
                $v['roi'] = $roi['百度']['roi'];
                $v['roi_count'] = $roi['百度']['roi_count'];
            } else {
                $v['roi'] = 0;
                $v['roi_count'] = 0;
            }
             switch ($v['effect']) {
                 case 1:
                     $effect = '恶意消耗';
                     break;
                 case 2:
                     $effect = '亏损消耗';
                     break;
                 case 3:
                     $effect = '无效消耗';
                     break;
                 case 4:
                     $effect = '有效消耗';
                     break;
                 case 5:
                     $effect = '优质消耗';
                     break;
                 default:
                     $effect = '';

             }
            $v['effect'] = $effect;
            $list[$k] = $v;
            $data['list'][$v['uid']][$v['family']][] = $v;
        }
        $data['list'] = array_values($data['list']);
        foreach ($data['list'] as $k =>$v) {
            $data['count'][$k] = 0;
            foreach ($v as $kk =>$vv) {
                $data['count'][$k] += count($vv);
            }
            $data['list'][$k] = array_values($v);
        }

        $page = $list->render();
        $family = db('gzh_family')->column('family','id');
        $userlist  = db('member');
        if(!in_array($uid, [1,52,53])){
            $userlist = $userlist->where('pid', $uid)->where('uid', '<>', $uid);
        }
        $userlist = $userlist->column("uid,username");

        // 汇总数据处理
        $sum = [
            'consume' => 0,
            'income' => 0,
            'income_one' => 0,
        ];
        foreach ($detailList as $k => $v) {
            $sum['consume'] += $v['consume'];
            $extensionId = explode(',', $v['extension_id']);
            $sum['income_one'] += db('gzh_extension')->where('detail_id', $v['id'])
                ->whereIn('extension_id', $extensionId)->sum('income_one');
            $sum['income'] += db('gzh_extension')->where('detail_id', $v['id'])
                ->whereIn('extension_id', $extensionId)->sum('income');
        }

        $this->assign(compact('data','list', 'page','gzhList', 'book', 'family', 'userlist','consumeCount', 'incomeOne', 'incomeCount','startDate, endDate','sum'));
        $this->setMeta("账号管理");
        return view('statistics/'.$action );
    }

    /**
     * Notes: 获取消耗标识
     * @param int $roi roi 系统设置
     * @param int $roiCount 总roi 系统设置
     * @param $proportion 总回收
     * @param $consume 总消耗
     * @return int|string
     * @since: 2022/12/2 9:16
     * @author: Zhu
     */
    private function getEffect($roi = 0, $roiCount = 0, $oneProportion, $proportion, $consume)
    {
        // 浮点转整形
        $roi = $roi * 10000;
        $roiCount = $roiCount * 10000;
        $oneProportion = $oneProportion * 10000;
        $proportion = $proportion * 10000;
        $effect = 3;
        if (($roi * 0.35 > $oneProportion || $proportion < $roiCount) && $consume >= 600) {
            $effect = '1';
        }
        if ((($roi * 0.7 > $oneProportion && $roi * 0.35 <= $oneProportion) || ($proportion < $roiCount)) && ($consume >= 400 && $consume < 600)) {
            $effect = '2';
        }
        if ($roi * 0.7 <= $oneProportion && $proportion < $roiCount) {
            $effect = '3';
        }
        if ($roi <= $oneProportion || $proportion >= $roiCount) {
            $effect = '4';
        }
        if ($roi * 2 <= $oneProportion || ($roiCount * 2 <= $proportion)) {
            $effect = '5';
        }
        return $effect;
    }

    /**
     * Notes:新增
     * User: zhu
     * Date: 2022/11/25
     * Time: 10:23
     */
    public function add() {
        if(IS_POST) {
            $post = input('post.');
            $validate = new Validate([
                'operate'  => 'require|number',
                'extension_id' => 'require',
                'consume' => 'require|float',
                'book_id' => 'require|number',
                'family' => 'require|alphaDash',
                'extension_date' => 'require|dateFormat:Y-m-d',
                'price' => 'float',
                'rate' => 'float',
                'cost' => 'float',
                'rate' => 'float',
                'point' => 'float',
            ],[
                'operate.require' => '请选择公众号',
                'book_id.require' => '请选择书籍',
                'extension_id.require' => '请输入推广ID，多个推广id用逗号隔开',
                'consume.require' => '请输入消耗',
                'consume.float' => '消耗必须是数值',
                'family.require' => '请输入户',
                'extension_date.require' => '请选择推广日期',
                'price.float' => '粉价必须是数值',
                'point.float' => '单点必须是数值',
                'cost.float' => '调起成本必须是数值',
                'rate.float' => '付费率必须是数值',
            ]);
            if (!$validate->check($post)) {
                return $this->error($validate->getError());
            }
            foreach ($post as $k => $v) {
                $post[$k] = trim($v);
            }
            $post['extension_id'] = str_replace( '，', ',',trim($post['extension_id'], ','));
            $post['create_time'] = time();
            $post['official_account_id'] = $post['operate'];
            $post['refresh'] = 1;

            $post['uid'] = session('user_auth.uid')?session('user_auth.uid'):1;
            $detailId = db('gzh_material_detail')->insertGetId($post);
            $family = db('gzh_family')->where('family', $post['family'])->find();
            if (!$family) {
                db('gzh_family')->insert([
                    'family' => $post['family'],
                    'uid' => session('user_auth.uid'),
                    'create_time' => time()
                ]);
            }
            $data['key'] = $this->key;
            $data['time'] = $post['extension_date'];
            $count = 0;
            $oneCount = 0;
            foreach (explode(',', $post['extension_id']) as $k => $v) {
                $data['tid'] = $v;
                // 获取公众号对应的推广总收入
                $extensionInfo = $this->curlRequest($this->url, $data);
                if ($extensionInfo['code'] == 1) {
                    db('gzh_extension')->insert([
                        'extension_id' => $v,
                        'income' => $extensionInfo['data']['income'],
                        'income_one' => $extensionInfo['data']['income_one'],
                        'income_two' => $extensionInfo['data']['income_two'],
                        'income_three' => $extensionInfo['data']['income_three'],
                        'extension_date' => $post['extension_date'],
                        'detail_id' => $detailId,
                        'create_time' => time()
                    ]);
                    $count += $extensionInfo['data']['income'];
                    $oneCount += $extensionInfo['data']['income_one'];
                }
            }
            $book = db('ads_material_book')->where('id', $post['book_id'])->find();
            $one_proportion = $oneCount == 0 ? 0 : $oneCount / $post['consume'] * 100;
            $proportion = $count == 0 ? 0 : $count / $post['consume'] * 100;
            if ($book) {
                $book = json_decode($book['roi'], true);
                if (isset($book['百度'])) {
                    $roi = $book['百度']['roi'];
                    $roiCount = $book['百度']['roi_count'];
                } else {
                    $roi = 0;
                    $roiCount = 0;
                }
                $effect = $this->getEffect($roi, $roiCount, $one_proportion, $proportion, $post['consume']);
                db('gzh_material_detail')->where('id', $detailId)->update(['effect' => $effect]);
            }
            return $this->success("成功！");
        }
        return $this->error("失败！");
    }

    /**
     * Notes: 修改
     * User: zhu
     * Date: 2022/11/25
     * Time: 10:23
     * @param
            k:推广链接id
            time:推广开始时间

     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function edit(){
        if(IS_POST){
            $post = input('post.');
            foreach ($post as $k => $v) {
                $post[$k] = trim($v);
            }
            if($post['id']){
                $validate = new Validate([
                    'operate'  => 'require|number',
                    'extension_id' => 'require',
                    'consume' => 'require|float',
                    'book_id' => 'require|number',
                    'family' => 'require|alphaDash',
                    'extension_date' => 'require|dateFormat:Y-m-d',
                    'refresh' => 'require|number',
                    'price' => 'float',
                    'rate' => 'float',
                    'cost' => 'float',
                    'rate' => 'float',
                    'point' => 'float',
                ],[
                    'operate.require' => '请选择公众号',
                    'book_id.require' => '请选择书籍',
                    'extension_id.require' => '请输入推广ID，多个推广id用逗号隔开',
                    'consume.require' => '请输入消耗',
                    'consume.float' => '消耗必须是数值',
                    'family.require' => '请输入户',
                    'extension_date.require' => '请选择推广日期',
                    'price.float' => '粉价必须是数值',
                    'point.float' => '单点必须是数值',
                    'cost.float' => '调起成本必须是数值',
                    'rate.float' => '付费率必须是数值',
                ]);
                if (!$validate->check($post)) {
                    return $this->error($validate->getError());
                }
                $post['extension_id'] = str_replace( '，', ',', $post['extension_id']);
                $post['extension_id'] = trim($post['extension_id'], ',');
                $post["update_time"] = time();
                $post["official_account_id"] = $post['operate'];
                db('gzh_material_detail')->where("id", $post['id'])->update($post);

                $family = db('gzh_family')->where('family', $post['family'])->find();
                if (!$family) {
                    db('gzh_family')->insert([
                        'family' => $post['family'],
                        'uid' => session('user_auth.uid'),
                        'create_time' => time()
                    ]);
                }
                $data['key'] = $this->key;
                $data['time'] = $post['extension_date'];
                $count = 0;
                $one_proportion = 0;
                foreach (explode(',', $post['extension_id']) as $k => $v) {
                    $data['tid'] = $v;
                    // 获取公众号对应的推广总收入
                    $extensionInfo = $this->curlRequest($this->url, $data);
                    if ($extensionInfo['code'] == 1) {
                        $isHave = db('gzh_extension')->where('detail_id', $post['id'])->where('extension_id', $v)->find();
                        if ($isHave) {
                            db('gzh_extension')->where('extension_id', $v)->where('detail_id', $post['id'])->update([
                                'extension_date' => $post['extension_date'],
                                'income' => $extensionInfo['data']['income'],
                                'income_one' => $extensionInfo['data']['income_one'],
                                'income_two' => $extensionInfo['data']['income_two'],
                                'income_three' => $extensionInfo['data']['income_three'],
                                'update_time' => time()
                            ]);
                        } else {
                            db('gzh_extension')->insert([
                                'extension_id' => $v,
                                'income' => $extensionInfo['data']['income'],
                                'income_one' => $extensionInfo['data']['income_one'],
                                'income_two' => $extensionInfo['data']['income_two'],
                                'income_three' => $extensionInfo['data']['income_three'],
                                'extension_date' => $post['extension_date'],
                                'detail_id' => $post['id'],
                                'create_time' => time()
                            ]);
                        }
                        $count += $extensionInfo['data']['income'];
                        $one_proportion += $extensionInfo['data']['income_one'];
                    }
                }

                $effect = 0;
                $book = db('ads_material_book')->where('id', $post['book_id'])->find();
                $proportion = $count == 0 ? 0 : $count / $post['consume'] * 100;
                $oneProportion = $one_proportion == 0 ? 0 : $one_proportion / $post['consume'] * 100;
                if ($book) {
                    $book = json_decode($book['roi'], true);
                    if (isset($book['百度'])) {
                        $roi = $book['百度']['roi'];
                        $roiCount = $book['百度']['roi_count'];
                    } else {
                        $roi = 0;
                        $roiCount = 0;
                    }
                    $effect = $this->getEffect($roi, $roiCount, $oneProportion, $proportion, $post['consume']);
                }
                db('gzh_material_detail')->where('id', $post['id'])->update(['effect'=>$effect]);
                return $this->success("修改成功！");
            }
        }
        return $this->error("失败！");
    }


    /**
     * Notes: 请求外部接口
     * User: zhu
     * Date: 2022/11/25
     * Time: 10:23
     * @param $url
     * @param null $data
     * @return mixed
     */
    private function curlRequest($url, $data = null)
    {
        $postUrl = $url;
        $curl = curl_init();//初始化curl
        curl_setopt($curl, CURLOPT_URL,$postUrl);//抓取指定网页
        curl_setopt($curl, CURLOPT_HEADER, 0);//设置header
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_POST, 1);//
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);//参数
        $content = curl_exec($curl);
        curl_close($curl);
        return json_decode($content, true);
    }

    /**
     * Notes: 删除
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     * @author: Zhu
     * @since: 2022/12/1 10:11
     */
    public function del() {
        $id = $this->getArrayParam('id');
        if (empty($id)) {
            return $this->error("非法操作！");
        }
        $map['id'] = array('IN', $id);
        $result  = db('gzh_material_detail')->where($map)->delete();
        $result2  = db('gzh_extension')->whereIn('detail_id', $id)->delete();
        if (false !== $result && false !== $result2) {
            return $this->success("删除成功！");
        } else {
            return $this->error("删除失败！");
        }
    }

    /**
     * Notes:
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * @since: 2022/12/3 14:59
     * @author: Zhu
     */
    public function refresh() {
        $params = input('post.');
        $validate = new Validate([
            'operate'  => 'require|number',
            'extension_id' => 'require',
            'consume' => 'require|float',
            'book_id' => 'require|number',
            'family' => 'require|alphaDash',
            'extension_date' => 'require|dateFormat:Y-m-d',
            'refresh' => 'require|number',
            'price' => 'float',
            'rate' => 'float',
            'cost' => 'float',
            'rate' => 'float',
            'point' => 'float',
        ],[
            'operate.require' => '请选择公众号',
            'book_id.require' => '请选择书籍',
            'extension_id.require' => '请输入推广ID，多个推广id用逗号隔开',
            'consume.require' => '请输入消耗',
            'consume.float' => '消耗必须是数值',
            'family.require' => '请输入户',
            'extension_date.require' => '请选择推广日期',
            'price.float' => '粉价必须是数值',
            'point.float' => '单点必须是数值',
            'cost.float' => '调起成本必须是数值',
            'rate.float' => '付费率必须是数值',
        ]);
        if (!$validate->check($params)) {
            return $this->error($validate->getError());
        }
        foreach ($params as $k => $v) {
            $params[$k] = trim($v);
        }
        $data = [
            'official_account_id' => $params['operate'],
            'family' => $params['family'],
            'book_id' => $params['book_id'],
            'extension_id' => $params['extension_id'],
            'consume' => $params['consume'],
            'point' => $params['point'],
            'cost' => $params['cost'],
            'price' => $params['price'],
            'rate' => $params['rate'],
            'extension_date' => $params['extension_date'],
            'uid' => session('user_auth.uid'),
            'pid' => $params['id'],
            'create_time' => time()
        ];

        $isRefresh = db('gzh_material_detail')->where("id", $params['id'])->value('refresh');
        if ($isRefresh == 2) {
            return $this->error('当前数据已更新过，请刷新页面');
        }
        db('gzh_material_detail')->where("id", $params['id'])
            ->update(['refresh'=> 2, 'update_time'=>time()]);
        $detailId = db('gzh_material_detail')->insertGetId($data);

        $extension_id = explode(',', $data['extension_id']);
        $data['key'] = $this->key;
        $data['time'] = $data['extension_date'];
        $count = 0;
        $one_proportion = 0;
        foreach ($extension_id as $k => $v) {
            $data['tid'] = $v;
            // 获取公众号对应的推广总收入
            $extensionInfo = $this->curlRequest($this->url, $data);
            if ($extensionInfo['code'] == 1) {
                db('gzh_extension')->insert([
                    'extension_id' => $v,
                    'income' => $extensionInfo['data']['income'],
                    'income_one' => $extensionInfo['data']['income_one'],
                    'income_two' => $extensionInfo['data']['income_two'],
                    'income_three' => $extensionInfo['data']['income_three'],
                    'extension_date' => $data['extension_date'],
                    'detail_id' => $detailId,
                    'create_time' => time()
                ]);
                $count += $extensionInfo['data']['income'];
                $one_proportion += $extensionInfo['data']['income_one'];
            }
        }
        $effect = 0;
        $proportion = $count == 0 ? 0 : $count / $data['consume'] * 100;
        $oneProportion = $one_proportion == 0 ? 0 : $one_proportion / $data['consume'] * 100;
        $book = db('ads_material_book')->where('id', $data['book_id'])->find();
        if ($book) {
            $book = json_decode($book['roi'], true);
            if (isset($book['百度'])) {
                $roi = $book['百度']['roi'];
                $roiCount = $book['百度']['roi_count'];
            } else {
                $roi = 0;
                $roiCount = 0;
            }
            $effect = $this->getEffect($roi, $roiCount, $oneProportion, $proportion, $data['consume']);
        }
        $result = db('gzh_material_detail')->where("id", $detailId)->update(['effect'=>$effect]);
        if (false !== $result) {
            return $this->success("成功！");
        } else {
            return $this->error("失败！");
        }
    }

    /**
     * Notes: 重新拉取数据
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * @since: 2022/12/6 18:02
     * @author: Zhu
     */
    public function updateData()
    {
        $id = request()->param('id');
        $ids = explode(',', $id);

        if (empty($ids)) {
            return $this->error("非法操作！");
        }

        $detail = db('gzh_material_detail')
            ->where('refresh', 1)
            ->whereIn('id', $ids)
            ->select();

        $params['key'] = $this->key;
        $url = $this->url;
        foreach ($detail as $k => $v) {
            $params['time'] = $v['extension_date'];
            $count = 0;
            $one_proportion = 0;
            foreach (explode(',', $v['extension_id']) as $extensionId) {
                $params['tid'] = $extensionId;
                // 获取公众号对应的推广总收入
                $extensionInfo = $this->curlRequest($url, $params);
                if ($extensionInfo['code'] == 1) {
                    $isHave = db('gzh_extension')
                        ->where('detail_id', $v['id'])
                        ->where('extension_id', $extensionId)
                        ->find();
                    if ($isHave) {
                        db('gzh_extension')
                            ->where('extension_id', $extensionId)->where('detail_id', $v['id'])
                            ->update([
                                'extension_date' => $v['extension_date'],
                                'income' => $extensionInfo['data']['income'],
                                'income_one' => $extensionInfo['data']['income_one'],
                                'income_two' => $extensionInfo['data']['income_two'],
                                'income_three' => $extensionInfo['data']['income_three'],
                                'update_time' => time()
                            ]);
                    } else {
                        db('gzh_extension')->insert([
                            'extension_id' => $extensionId,
                            'income' => $extensionInfo['data']['income'],
                            'income_one' => $extensionInfo['data']['income_one'],
                            'income_two' => $extensionInfo['data']['income_two'],
                            'income_three' => $extensionInfo['data']['income_three'],
                            'extension_date' => $v['extension_date'],
                            'detail_id' => $v['id'],
                            'create_time' => time()
                        ]);
                    }
                    $count += $extensionInfo['data']['income'];
                    $one_proportion += $extensionInfo['data']['income_one'];
                } else {
                    echo $extensionId . $extensionInfo['msg'];
                }
                $effect = 0;
                $proportion = $count == 0 ? 0 : $count / $v['consume'] * 100;
                $oneProportion = $one_proportion == 0 ? 0 : $one_proportion / $v['consume'] * 100;
                $book = db('ads_material_book')->where('id', $v['book_id'])->find();
                if ($book) {
                    $book = json_decode($book['roi'], true);
                    if (isset($book['百度'])) {
                        $roi = $book['百度']['roi'];
                        $roiCount = $book['百度']['roi_count'];
                    } else {
                        $roi = 0;
                        $roiCount = 0;
                    }
                    $effect = $this->getEffect($roi, $roiCount, $oneProportion, $proportion, $v['consume']);
                }
                db('gzh_material_detail')->where('id', $v['id'])->update(['effect'=>$effect]);
            }

        }
        return $this->success("刷新成功！");

    }

    /**
     * Notes: 批量刷新有效表示
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * @since: 2022/12/14 11:50
     * @author: Zhu
     */
    public function refreshRoi()
    {
        $id = request()->param('id');
        $ids = explode(',', $id);

        if (empty($ids)) {
            return $this->error("非法操作！");
        }

        $detail = db('gzh_material_detail')
            ->where('refresh', 1)
            ->whereIn('id', $ids)
            ->select();

        foreach ($detail as $k => $v) {
            $count = 0;
            $one_proportion = 0;

            foreach (explode(',', $v['extension_id']) as $extensionId) {
                $extensionInfo = db('gzh_extension')
                    ->where('extension_id', $extensionId)->where('detail_id', $v['id'])
                    ->find();
                $count += $extensionInfo['income'];
                $one_proportion += $extensionInfo['income_one'];
            }

            $proportion = $count == 0 ? 0 : $count / $v['consume'] * 100;
            $oneProportion = $one_proportion == 0 ? 0 : $one_proportion / $v['consume'] * 100;

            $effect = 0;
            $book = db('ads_material_book')->where('id', $v['book_id'])->find();
            if ($book) {
                $book = json_decode($book['roi'], true);
                if (isset($book['百度'])) {
                    $roi = $book['百度']['roi'];
                    $roiCount = $book['百度']['roi_count'];
                } else {
                    $roi = 0;
                    $roiCount = 0;
                }
                $effect = $this->getEffect($roi, $roiCount, $oneProportion, $proportion, $v['consume']);
            }
            db('gzh_material_detail')->where('id', $v['id'])->update(['effect'=>$effect]);

        }
        return $this->success("刷新成功！");
    }

}